package org.ap.demo.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

@Configuration
@EnableResourceServer
public  class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

	private static final String DEMO_RESOURCE_ID = "api";
	@Autowired 
	private CustomAccessDeniedHandler customAccessDeniedHandler;
	@Value("${token.endpoint.url}")
	private String checkTokenUrl;
	@Value("${token.check:true}")
	private boolean tokenCheck;
	
	@Bean
    public RemoteTokenServices remoteTokenServices() {
		RemoteTokenServices tokenServices = new CustomizedRemoteTokenServices();
//        tokenServices.setClientId("resource_server");
//        tokenServices.setClientSecret("abc123");
//        tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        tokenServices.setCheckTokenEndpointUrl(checkTokenUrl);
        tokenServices.setAccessTokenConverter(new DefaultAccessTokenConverter());
        return tokenServices;
    }
	
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
        resources.authenticationEntryPoint(new AuthExceptionEntryPoint())
                .accessDeniedHandler(customAccessDeniedHandler);
        CustomBearerTokenExtractor tokenExtractor = new CustomBearerTokenExtractor();
        resources.tokenExtractor(tokenExtractor);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
    	if(!tokenCheck) {
    		http.authorizeRequests().anyRequest().permitAll().
    		and().csrf().disable();
    	}else {
    		http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/hello").hasAuthority("hello")
            .antMatchers("/api/greeting").hasAuthority("greeting")
            .anyRequest().authenticated()
            .and()
            .requestMatchers().antMatchers("/api/**");
    	}
        
    }
}
